package com.tiecode.lower;

import com.android.tools.r8.lower.CompilationMode;
import com.android.tools.r8.lower.D8Command;
import com.android.tools.r8.lower.DiagnosticsHandler;
import com.android.tools.r8.lower.OutputMode;
import com.rapid.api.project.toolchain.android.d8.D8CompileParams;
import com.rapid.api.project.toolchain.android.d8.D8Compiler;

public class LowerD8Compiler implements D8Compiler {

    @Override
    public boolean compile(D8CompileParams params, OnExecutionCallback callback) {
        try {
            D8Command.Builder builder = D8Command.builder(new DiagnosticsHandler() {
                @Override
                public void error(com.android.tools.r8.lower.Diagnostic error) {
                    if (callback != null) {
                        callback.onPrintLine(LogLevel.ERROR, error.getDiagnosticMessage());
                    }
                }

                @Override
                public void warning(com.android.tools.r8.lower.Diagnostic warning) {
                    if (callback != null) {
                        callback.onPrintLine(LogLevel.WARNING, warning.getDiagnosticMessage());
                    }
                }
            });
            builder.addProgramFiles(params.programFiles);
            if (params.libraryFiles != null) {
                builder.addLibraryFiles(params.libraryFiles);
            }
            if (params.classpathFiles != null) {
                builder.addClasspathFiles(params.classpathFiles);
            }
            builder.setMode(params.debug ? CompilationMode.DEBUG : CompilationMode.RELEASE);
            builder.setMinApiLevel(params.minApiLevel);
            switch (params.outputKind) {
                case DexIndexed:
                    builder.setOutput(params.outputDir, OutputMode.DexIndexed);
                    break;
                case DexFilePerClass:
                    builder.setOutput(params.outputDir, OutputMode.DexFilePerClass);
                    break;
                case DexFilePerClassFile:
                    builder.setOutput(params.outputDir, OutputMode.DexFilePerClassFile);
                    break;
                case ClassFile:
                    builder.setOutput(params.outputDir, OutputMode.ClassFile);
                    break;
            }
            if (params.proguardInputMapFile != null) {
                builder.setProguardInputMapFile(params.proguardInputMapFile);
            }
            com.android.tools.r8.lower.D8.run(builder.build());
        } catch (Exception e) {
            e.printStackTrace();
            if (callback != null) {
                callback.onPrintLine(LogLevel.ERROR, e.getMessage());
            }
            return false;
        }
        return true;
    }
}
